/*
 *
 * Copyright (C) 2012 Walter Lütgenau
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *      http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * 
 */
package offset.nodes.server.view.list;

import offset.nodes.server.search.controller.QueryAttribute;
import java.util.StringTokenizer;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.jcr.Node;
import javax.jcr.Property;
import javax.jcr.PropertyIterator;
import javax.jcr.PropertyType;
import javax.jcr.RepositoryException;
import javax.servlet.http.HttpServletRequest;
import offset.nodes.Constants;
import offset.nodes.server.search.view.SearchBean;
import offset.nodes.server.view.FacesUtils;

/**
 *
 * @author Walter Lütgenau
 */
public class TextNodeConverter implements Converter {

    public Object getAsObject(FacesContext arg0, UIComponent arg1, String arg2) {
        return null;
    }

    public String getAsString(FacesContext arg0, UIComponent arg1, Object object) {
        return rowToString((Node) object);
    }

    protected String normalizePattern(String pattern) {
        if (pattern.charAt(0) == '\"' && pattern.charAt(pattern.length() - 1) == '\"')
            return pattern.substring(1, pattern.length() - 1);
        return pattern;
    }

    protected String highlightPattern(String value, String pattern) {
        int index;

        pattern = normalizePattern(pattern);

        StringBuffer result = new StringBuffer();
        StringTokenizer tokenizer = new StringTokenizer(value, "\n.", true);
        while (tokenizer.hasMoreTokens()) {
            String token = tokenizer.nextToken();

            boolean found = false;
            String upper = token.toUpperCase();
            while ((index = upper.indexOf(pattern.toUpperCase())) >= 0) {
                found = true;

                result.append(token.substring(0, index));
                result.append("<b>");
                result.append(token.substring(index, index + pattern.length()));
                result.append("</b>");

                token = token.substring(index + pattern.length());
                upper = token.toUpperCase();
            }

            if (found) {
                result.append(token);
                if (tokenizer.hasMoreTokens())
                    result.append(tokenizer.nextToken());
            }
        }

        return result.toString();
    }

    public String rowToString(Node node) {
        StringBuffer result = new StringBuffer();

        try {
            PropertyIterator i = node.getProperties();
            while (i.hasNext()) {
                Property property = i.nextProperty();

                String relativePath = property.getPath().substring(property.getPath().lastIndexOf(Constants.PATH_SEPARATOR) + 1);
                if (!node.hasProperty(relativePath) || property.getType() != PropertyType.STRING)
                    continue;

                if (property.getDefinition().isMultiple()) {
                    if (property.getValues().length == 0)
                        continue;
                    
                    result.append(highlightPattern((String) property.getValues()[0].getString(), getPattern()));
                }
                else
                    result.append(highlightPattern((String) property.getString(), getPattern()));
            }

            return result.toString();
        } catch (RepositoryException e) {
            throw new RuntimeException(e);
        }
    }

    public String getPattern() {
        return ((SearchBean) FacesUtils.getBean(SearchBean.class)).getQuery();
    }
}
